//
//  RegisterViewController.m
//  ChengXinBao
//
//  Created by RongZhou on 17/3/8.
//  Copyright © 2017年 RongZhou. All rights reserved.
//

#import "RegisterViewController.h"
#import "VerificationCodeBtn.h"
#import "UITextField+LXDAdjust.h"
#import <Masonry.h>
#import <AFNetworking.h>
@interface RegisterViewController ()<UITextFieldDelegate>
@property(nonatomic,strong)UITextField *usernameTextfiled;
@property(nonatomic,strong)UITextField *secrectTextfiled;
@property(nonatomic,strong)UITextField *confirmsecrectTextfiled;
@property(nonatomic,strong)UITextField *phoneNumberTextfiled;
@property(nonatomic,strong)UITextField *
    codeTextfiled;
@property(nonatomic,copy)NSString *rescode;
@end

@implementation RegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createUIView];
    UISwipeGestureRecognizer *swip = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(dismissTheRegisterVc)];
    [self.view addGestureRecognizer:swip];
}
-(void)dismissTheRegisterVc{
    [self dismissViewControllerAnimated:YES completion:nil];
}
/**
 *  构建页面UI
 */
-(void)createUIView{
    UIImageView *bgImageView = [[UIImageView alloc] initWithFrame:self.view.bounds];
    bgImageView.image = [UIImage imageNamed:@"loginBg"];
    [self.view addSubview:bgImageView];
    [self.view insertSubview:bgImageView atIndex:0];
    __weak typeof(self) weakSelf = self;
    NSArray *textFiledArra = @[weakSelf.codeTextfiled,weakSelf.phoneNumberTextfiled,weakSelf.confirmsecrectTextfiled,weakSelf.secrectTextfiled,weakSelf.usernameTextfiled];
    NSArray *textFildPlace = @[@"请输入验证码",@"请输入手机号",@"确认密码",@"请输入密码",@"请输入用户名"];
    NSArray *iconArray = @[@"tab_phone1",@"tab_phone",@"tab_password",@"tab_password",@"tab_username"];
    NSMutableArray *whiteViews = [NSMutableArray array];
    for (NSInteger i = 0; i < textFiledArra.count; i++) {
        UIView *whiteView = [[UIView alloc] init];
        whiteView.backgroundColor = [UIColor whiteColor];
        whiteView.layer.cornerRadius = 30;
        whiteView.layer.masksToBounds = YES;
        whiteView.layer.borderWidth = 1.0f;
        whiteView.layer.borderColor = [UIColor lightGrayColor].CGColor;
        UIImageView *imageView = [[UIImageView alloc] init];
        imageView.image = [UIImage imageNamed:iconArray[i]];
        [whiteView addSubview:imageView];
        [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(whiteView.mas_centerY);
            make.left.equalTo(whiteView.mas_left).offset(10);
            make.width.mas_equalTo(32);
            make.height.mas_equalTo(32);
        }];
        UITextField *textFiled = textFiledArra[i];
        [textFiled setAutoAdjust:YES];
        textFiled.delegate = self;
        textFiled.placeholder = textFildPlace[i];
        [whiteView addSubview:textFiled];
        [textFiled mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(whiteView.mas_centerY);
                make.left.equalTo(imageView.mas_right).offset(10);
               make.height.mas_equalTo(40);
            if (i == 0) {
                make.width.mas_equalTo(100);
                [self createTimeButton:whiteView];
            }else{
                make.right.equalTo(whiteView.mas_right).offset(-2);
            }
             }];
        [weakSelf.view addSubview:whiteView];
        [whiteViews addObject:whiteView];
    }
    [whiteViews mas_distributeViewsAlongAxis:MASAxisTypeVertical withFixedItemLength:60 leadSpacing:ScreenHeight - 250 tailSpacing:ScreenHeight - 180];
    [whiteViews mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(weakSelf.view);
        make.width.mas_equalTo(ScreenWidth - 60);
    }];
    UIButton *registerbutton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:registerbutton];
    registerbutton.backgroundColor = [UIColor blueColor];
    registerbutton.layer.cornerRadius = 30;
    registerbutton.layer.masksToBounds = YES;
    [registerbutton setTitle:@"注册" forState:UIControlStateNormal];
    [registerbutton addTarget:self action:@selector(registerNewAccount) forControlEvents:UIControlEventTouchUpInside];
    [registerbutton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(30);
        make.right.equalTo(self.view.mas_right).offset(-30);
        make.bottom.equalTo(self.view.mas_bottom).offset(-100);
        make.height.mas_equalTo(60);
    }];
    
}
/**
 *  注册新用户点击事件
 */
-(void)registerNewAccount{
    if ([self.usernameTextfiled.text  isEqual: @""] || [self.secrectTextfiled.text  isEqual: @""] || [self.confirmsecrectTextfiled.text  isEqual: @""] || [self.phoneNumberTextfiled.text  isEqual: @""] || [self.codeTextfiled.text  isEqual: @""]
        ) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"您输入的信息不完全" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }else if (self.secrectTextfiled.text.length < 6){
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"密码长度至少6位" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }else if (![self.secrectTextfiled.text isEqual: self.confirmsecrectTextfiled.text]){
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"两次输入的密码不一致" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }else if (![self.codeTextfiled.text isEqual:self.rescode]){
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"验证码输入错误" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }else{
        [self logInWithPhoneNumber:self.phoneNumberTextfiled.text andPassword:self.secrectTextfiled.text AndUserName:self.usernameTextfiled.text];
    }
}
/**
 *  保存用户信息
 *
 *  @param phonenumber 手机号
 *  @param password    密码
 *  @param userName    用户名
 */
-(void)logInWithPhoneNumber:(NSString *)phonenumber andPassword:(NSString *)password AndUserName:(NSString *)userName{
    NSString *str = ServiceUrl@"/phoneUserApp/savePhoneUser";
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSDictionary *dict = @{@"phone":phonenumber,@"passWord":password,@"name":userName};
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:str parameters:dict progress:^(NSProgress * _Nonnull uploadProgress) {

    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"%@",dict);
        ALERT(@"注册成功");
        [self dismissViewControllerAnimated:YES completion:nil];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
    }];

}

#pragma mark-创建倒计时的按钮布局
-(void)createTimeButton:(UIView *)view{
    
    VerificationCodeBtn *timeBtn = [[VerificationCodeBtn alloc] initWithFrame:CGRectZero];
    [view addSubview:timeBtn];
    [timeBtn setBackgroundColor:ZColorRGB(220, 221, 222)];
    [timeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(view.mas_top).offset(0);
        make.bottom.equalTo(view.mas_bottom).offset(0);
        make.right.equalTo(view.mas_right).offset(-2);
        make.width.mas_equalTo(90);
    }];
    __block VerificationCodeBtn *blockBtn = timeBtn;
    timeBtn.clickblock = ^{
        //获取手机的验证码
        if ([_phoneNumberTextfiled.text isEqual:@""]) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"手机号码不能为空" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
        }else{
            [blockBtn startTimer];
            NSString *url = ServiceUrl@"/phoneUserApp/getRegisterCode";
            NSDictionary *param = @{@"phone":_phoneNumberTextfiled.text};
            AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
            manager.responseSerializer = [AFHTTPResponseSerializer serializer];
            [manager POST:url parameters:param progress:^(NSProgress * _Nonnull uploadProgress) {
                
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
                self.rescode = dict[@"code"];
                NSLog(@"我是验证码%@",self.rescode);
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                
            }];
        }
        
    };
}

#pragma mark -文本输入框初始化
-(UITextField *)usernameTextfiled{
    if (_usernameTextfiled == nil) {
        _usernameTextfiled = [[UITextField alloc] init];
    }
    return _usernameTextfiled;
}
-(UITextField *)secrectTextfiled{
    if (_secrectTextfiled == nil) {
        _secrectTextfiled = [[UITextField alloc] init];
    }
    return _secrectTextfiled;
}
-(UITextField *)confirmsecrectTextfiled{
    if (_confirmsecrectTextfiled == nil) {
        _confirmsecrectTextfiled = [[UITextField alloc] init];
    }
    return _confirmsecrectTextfiled;
}
-(UITextField *)phoneNumberTextfiled{
    if (_phoneNumberTextfiled == nil) {
        _phoneNumberTextfiled = [[UITextField alloc] init];
    }
    return _phoneNumberTextfiled;
}
-(UITextField *)codeTextfiled{
    if (_codeTextfiled == nil) {
        _codeTextfiled = [[UITextField alloc] init];
    }
    return _codeTextfiled;
}
#pragma mark - 文本输入框的代理方法
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}


@end
